package com.lh.item.controller;

import com.lh.common.pojo.PageResult;
import com.lh.item.pojo.BrandDo;
import com.lh.item.service.IBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author liuhe
 * @date 2020/06/18
 */
@RestController
@RequestMapping("brand")
public class BrandController {

    final IBrandService iBrandService;

    @Autowired
    public BrandController(IBrandService iBrandService) {
        this.iBrandService = iBrandService;
    }

    /**
     * 搜索品牌
     */
    @GetMapping("page")
    public ResponseEntity<PageResult<BrandDo>> queryBrandList(@RequestParam(value = "key", required = false) String key,
                                                              @RequestParam(value = "page", defaultValue = "0") Integer page,
                                                              @RequestParam(value = "rows", defaultValue = "10") Integer rows,
                                                              @RequestParam(value = "sortBy", required = false) String sortBy,
                                                              @RequestParam(value = "desc", required = false) Boolean desc) {
        PageResult<BrandDo> brands = iBrandService.queryBrandList(key, page, rows, sortBy, desc);
        return ResponseEntity.ok(brands);
    }

    /**
     * 根据商品分类查询品牌列表
     */
    @GetMapping("cid/{cid}")
    public ResponseEntity<List<BrandDo>> queryBrandByCid(@PathVariable(value = "cid", required = true) Long cid) {
        List<BrandDo> brandDos = iBrandService.queryBrandByCid(cid);
        if (CollectionUtils.isEmpty(brandDos)) {
            ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(brandDos);
    }

    /**
     * 根据品牌id结合，查询品牌信息
     *
     * @param ids
     * @return
     */
    @GetMapping("list")
    public ResponseEntity<List<BrandDo>> queryBrandByIds(@RequestParam("ids") List<Long> ids) {
        List<BrandDo> list = this.iBrandService.queryBrandByBrandIds(ids);
        if (list == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        return ResponseEntity.ok(list);
    }

    /**
     * 保存品牌信息
     * 加上@RequestBody会报415
     */
    @PostMapping
    public ResponseEntity<Boolean> saveBrand(/*@RequestBody*/ BrandDo brandDo, @RequestParam("cids") List<Long> cids) {
        boolean saveResult = this.iBrandService.saveBrand(brandDo, cids);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

}
